package common

import (
	"encoding/json"
	"fmt"
	"os"
	"runtime"
	"time"

	log "github.com/sirupsen/logrus"
)

const (
	Offset              = 0
	Limit               = 10000
	MasterName          = "master"
	SlaveName           = "slave"
	Online              = "online"
	Develop             = "develop"
	Local               = "local"
	Test                = "test"
	GCRDSHA_ENVIRONMENT = "GCRDSHA_ENVIRONMENT"
)

// orchestrator
const (
	ClusterInfo      = "clusters-info" // 获取所有mysql集群
	ClusterAliasInfo = "cluster/alias" // 获取指定mysql集群别名详细信息
	//增加非auto的方式
	GracefulMasterTakeoverAuto = "graceful-master-takeover-auto" // 手动切主,auto模式
	GracefulMasterTakeover     = "graceful-master-takeover"      // 手动切主,非auto模式
	RaftStatus                 = "raft-status"                   // 集群状态检查
	Discover                   = "discover"                      // 发现节点信息-检查复制状态
	Forget                     = "forget"                        // 忘记节点信息-检查复制状态
	Topology                   = "topology"                      // 发现节点信息-检查downtime状态
)

// vip
const (
	Vip       = "/portal/vpc-service/web/v1/vip"          // 创建vip
	Vips      = "/portal/vpc-service/web/v1/vips"         // 查询vip列表
	VipDelete = "/portal/vpc-service/web/v1/vip/"         // 删除vip
	VipBind   = "/portal/vpc-service/web/v1/vip/ecs/bind" // vip绑定Ecs
)

var (
	TTT *ResponseForHttpType
)

func GetFetchUrl() string {
	return AgentConfig.Orch.Url
}

func IsDevelop() bool {
	return GetEnvironment() == Develop
}

func IsOnline() bool {
	return GetEnvironment() == Online
}

func GetEnvironment() string {
	environment := os.Getenv(GCRDSHA_ENVIRONMENT)
	if environment != "" {
		return environment
	}
	return Local
}

type FetchHttpResponseTest struct {
	Content string `json:"content"`
}

type FetchHttpResponse struct {
	Content string `json:"content"`
}

func GetDateTimeInfo(format string) string {
	currentTime := time.Now()

	switch format {
	case "year":
		return fmt.Sprintf("%d", currentTime.Year())
	case "month":
		return fmt.Sprintf("%d", currentTime.Month())
	case "day":
		return fmt.Sprintf("%d", currentTime.Day())
	case "hour":
		return fmt.Sprintf("%d", currentTime.Hour())
	case "minute":
		return fmt.Sprintf("%d", currentTime.Minute())
	case "second":
		return fmt.Sprintf("%d", currentTime.Second())
	case "week":
		return currentTime.Weekday().String()
	case "formatDay":
		return currentTime.Format("2006-01-02")
	case "format":
		return currentTime.Format("2006-01-02 15:04:05")
	default:
		return "Invalid Format"
	}
}

func IsIpAddr(ipAddr string) bool {
	return true
}

type ResponseForHttpType struct {
}

type ResponseForHttp interface {
	GetResponseForHttp(b []byte, d any) error
}

func (t *ResponseForHttpType) GetResponseForHttp(b []byte, d any) error {
	if err := json.Unmarshal(b, &d); err != nil {
		log.WithFields(log.Fields{"err": err, "s": string(b), "d": d}).Error("GetResponseForHttp.json.Unmarshal error: ")
		return err
	}
	return nil
}

func Go(f func()) {
	defer GoDefer()
	f()
}

func GoDefer() {
	if r := recover(); r != nil {
		// 获取堆栈信息
		stack := make([]byte, 4096)
		length := runtime.Stack(stack, false)

		fmt.Printf("Recovered from panic: %v\n", r)
		fmt.Printf("Stack Trace:\n%s\n", stack[:length])
	}
}
